import datetime
import json
import time

import GlobalParam
from LogUtil import red_printLog, timePrintLog
from RedisHelper import RedisHelper
from SimpleWSManager import SimpleWSManager

redisHelper = RedisHelper(GlobalParam.redis_ip, GlobalParam.redis_port, GlobalParam.redis_db,
                          GlobalParam.redis_password)
# 存储所有合约信息
instrument_info_all = []

# 获取tick并传递
def get_tick():
    sws = SimpleWSManager()
    while True:
        try:
            tikerMarketData = GlobalParam.tickQueue.get()
            instrument_all = list(instrument_info_all.keys())
            if tikerMarketData["InstrumentID"] in instrument_all:
                if len(tikerMarketData["TradingDay"]) != 0 and len(tikerMarketData["UpdateTime"]) != 0:
                    redisHelper.setMapValue("ticker_" + tikerMarketData["InstrumentID"], tikerMarketData)
                    sws.disparcher(tikerMarketData["InstrumentID"], json.dumps(tikerMarketData))

        except Exception as e:
            red_printLog(e)


# 如果是无效数据，则返回True
def clean_data(pDepthMarketData):
    if '7*24' not in GlobalParam.broker_name:
        today = datetime.datetime.now().strftime('%Y-%m-%d')
        stamp = today + " " + pDepthMarketData.UpdateTime
        timeArray = time.strptime(stamp, "%Y-%m-%d %H:%M:%S")
        timeStamp = int(time.mktime(timeArray))
        now = int(time.time())
        now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        # 时间戳之差超过1分钟即认为是无效数据
        if abs(now - timeStamp) > 60:
            timePrintLog(f"marketdata delay : ID:{pDepthMarketData.InstrumentID}, Stamp:{stamp}, Now:{now_time}")
            return True
        else:
            return False


# 判断发送请求失败原因
def judge_ret(ret):
    if ret == -1:
        timePrintLog('失败原因：网络连接失败')
    elif ret == -2:
        timePrintLog('失败原因：表示未处理请求超过许可数')
    elif ret == -3:
        timePrintLog('失败原因：表示每秒发送请求数超过许可数')
    else:
        timePrintLog('失败原因：未知。\nret：{}'.format(ret))


def set_market_model(ticker):
    tikerMarketData = redisHelper.getEightMulitMapValue("ticker_" + ticker, 'TradingDay', 'LastPrice', 'BidPrice1',
                                                        'AskPrice1', 'SettlementPrice', 'UpdateTime', 'UpperLimitPrice',
                                                        'LowerLimitPrice')
    # 交易日
    if tikerMarketData[0] is None:
        return None

    pDepthMarketData = {
        'InstrumentID': ticker,
        'TradingDay': tikerMarketData[0],
        'LastPrice': tikerMarketData[1],
        'BidPrice1': tikerMarketData[2],
        'AskPrice1': tikerMarketData[3],
        'SettlementPrice': tikerMarketData[4],
        'UpdateTime': tikerMarketData[5],
        'UpperLimitPrice': tikerMarketData[6],
        'LowerLimitPrice': tikerMarketData[7]
    }

    return pDepthMarketData


def load():
    try:
        with open('./instrument/ExchangeID.json', 'r', encoding='utf8') as f:
            instrument_info_all = json.load(f)
            return instrument_info_all
    except Exception as e:
        print(e.__str__())
